package com.xbongbong.saas.model.impl;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.dao.FormConfigDao;
import com.xbongbong.pro.domain.entity.FormConfigEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.RepeatTypeEnum;
import com.xbongbong.saas.model.FormConfigModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/5/21 15:09
 * @since v1.0
 */
@Service("formConfigModel")
public class FormConfigModelImpl implements FormConfigModel {
    @Resource
    private FormConfigDao formConfigDao;
    @Resource
    private PaasFormModel paasFormModel;

    @Resource
    private PaasRedisHelper paasRedisHelper;


    @Override
    public Integer deleteByKey(Long key, String corpid) {
        return formConfigDao.deleteByKey(key, corpid);
    }

    @Override
    public Integer deleteBatch(List<Long> idIn, String corpid) {
        return formConfigDao.deleteBatch(idIn, corpid);
    }

    @Override
    public FormConfigEntity getByKey(Long key, String corpid) {
        return formConfigDao.getByKey(key, corpid);
    }

    @Override
    public Integer insert(FormConfigEntity entity) throws XbbException {
        Long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        return formConfigDao.insert(entity);
    }

    @Override
    public Integer update(FormConfigEntity entity) throws XbbException {
        Long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        return formConfigDao.update(entity);
    }

    @Override
    public List<FormConfigEntity> insertBatch(List<FormConfigEntity> list) {
        formConfigDao.insertBatch(list);
        return list;
    }

    @Override
    public List<FormConfigEntity> findEntitys(Map<String, Object> param) {
        return formConfigDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return formConfigDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public Integer save(FormConfigEntity entity) throws XbbException {
        if (entity.getId() == null || entity.getId().equals(0L)) {
            return insert(entity);
        }
        return update(entity);
    }

    @Override
    public FormConfigEntity getEntityByFormId(String corpid, Long formId, String config) {
        return formConfigDao.getEntityByFormId(corpid, formId, config);
    }
    
    @Override
    public List<FormConfigEntity> getButtonEntityByFormId(String corpid, Long formId, List<String> configList){
        return formConfigDao.getButtonEntityByFormId(corpid,formId,configList);
    }


    @Override
    public FormConfigEntity getEntityByBusinessType(String corpid, Integer businessType, String config) {
        return formConfigDao.getEntityByBusinessType(corpid, businessType, config);
    }

    @Override
    public void updateBatch(List<FormConfigEntity> list, String corpid) {
        formConfigDao.updateBatch(list, corpid);
    }

    /**
     * 更新表单模板的查重配置
     * @author xingxing.xiao
     * @param param
     * @return
     */
    @Override
    public Integer updateRepeatType(Map<String, Object> param) {
        return formConfigDao.updateRepeatType(param);
    }

    @Override
    public boolean hasBeenEnable(String corpid, String config, String positiveNumber, Long formId) throws XbbException {
        FormConfigEnum formConfigEnum = FormConfigEnum.getByConfig(config);
        if (formConfigEnum == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "无此表单配置");
        }

        FormConfigEntity entity;
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("config", config);
        param.put("formId", formId);
        List<FormConfigEntity> list = findEntitys(param);
        if (list.isEmpty()) {
            return false;
        }
        entity = list.get(0);
        return Objects.equals(entity.getConfigValue(), positiveNumber);
    }

    @Override
    public FormConfigEntity getByConfig(String config, String corpid, Long formId, Integer saasMark, Integer businessType) {
        return formConfigDao.getByConfig(config, corpid, formId, saasMark, businessType );
    }

    @Override
    public void insertRepeatType(String corpid, Long menuId, String config, Integer businessType) {
        // 查出 formId 插入 tb_form_config 表
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("columns", "id");
        param.put("corpid", corpid);
        param.put("menuId", menuId);
        param.put("del", 0);
        List<PaasFormEntityExt> formEntitys = paasFormModel.getByBusinessTypes(param);
        List<FormConfigEntity> formConfigEntityList = new ArrayList<>();
        for (PaasFormEntityExt formEntity : formEntitys) {
            FormConfigEntity configEntity = new FormConfigEntity(corpid, formEntity.getId(), SaasMarkEnum.SAAS.getCode(), businessType, config, RepeatTypeEnum.REPEAT_ALL.getType().toString());
            formConfigEntityList.add(configEntity);
        }
        insertBatch(formConfigEntityList);
    }

    @Override
    public void updateAllRepeatType(String corpid, String config, String repeatType) {
        // 最简单的方式是用 corpid 和 config 来匹配符合条件的表单配置（不然就是根据 menuId 查出下面所有的 formId，再更新所有表单的配置）
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("config", config);
        param.put("configValue", repeatType);
        param.put("updateTime", DateTimeUtil.getInt());
        updateRepeatType(param);
    }


    @Override
    public String getConfigValueByRedis(String config, String corpid, Long formId, Integer saasMark, Integer businessType, String defaultValue) {
        String key = corpid+ StringConstant.UNDER_LINE+businessType+StringConstant.UNDER_LINE+formId;
        String redisValue = paasRedisHelper.getValue(config, key);
        if (StringUtil.isEmpty(redisValue)) {
            FormConfigEntity formConfigEntity = getByConfig(config, corpid, formId, saasMark, businessType);
            if (Objects.nonNull(formConfigEntity)) {
                paasRedisHelper.setValue(config, key, formConfigEntity.getConfigValue(), TimeConstant.TEN_MINUTE_DURATION);
            } else {
                paasRedisHelper.setValue(config, key, defaultValue, TimeConstant.TEN_MINUTE_DURATION);
                return defaultValue;
            }
        }
        return redisValue;
    }

    @Override
    public Integer save(String config, String corpid, Long formId, Integer saasMark, Integer businessType, String value) throws XbbException {
        Integer integer;
        FormConfigEntity formConfigEntity = getByConfig(config, corpid, formId, saasMark, businessType);
        if (Objects.isNull(formConfigEntity)) {
            FormConfigEntity configEntity = new FormConfigEntity(corpid, formId, saasMark, businessType, config, value);
            integer = insert(configEntity);
        } else {
            FormConfigEntity configEntity = new FormConfigEntity();
            configEntity.setId(formConfigEntity.getId());
            configEntity.setCorpid(corpid);
            configEntity.setConfigValue(value);
            integer = update(configEntity);
        }
        String key = corpid+ StringConstant.UNDER_LINE+businessType+StringConstant.UNDER_LINE+formId;
        paasRedisHelper.setValue(RedisPrefixConstant.ASSIGNMENT_RULES, key, value, TimeConstant.TEN_MINUTE_DURATION);
        return integer;
    }
}
